package com.zuikaku.nettydemo.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class Main {


    public static void main(String[]args)
    {
        NioEventLoopGroup bossGroup =null;
        NioEventLoopGroup workerGroup = null;
        try {
            //1创建我们两个线程组，bossGroup，workerGroup
            bossGroup = new NioEventLoopGroup(1);
            workerGroup = new NioEventLoopGroup();
            //2创建服务端启动助手
            ServerBootstrap bootstrap = new ServerBootstrap();
            //3.将线程组设置给启动助手
            bootstrap.group(bossGroup, workerGroup)
                    //4.指定通信channel的类型
                    .channel(NioServerSocketChannel.class)
                    //5.指定channel初始化器
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //6.完成channel的初始化，以及去指定编解码器和自定义handler
                            socketChannel.pipeline().addLast(new StringEncoder());
                            socketChannel.pipeline().addLast(new StringDecoder());
                            //todo 添加自定义处理器
                            socketChannel.pipeline().addLast(new MyNettyServerHandler());
                        }
                    });
            //7.服务端启动助手绑定端口，并且设置同步方式运行，获得返回的channelFuture对象
            ChannelFuture channelFuture = bootstrap.bind(7788).sync();
            System.out.println("--服务开启了--");
            //8.配置channelFuture在未来以同步方式关闭
            channelFuture.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
